//
//  UITextField+Extenstion.swift
//  KPBaseProject
//
//  Created by Kipp Dev on 2018/4/12.
//  Copyright © 2018年 Kipp. All rights reserved.
//

import Foundation
import Closures
import RxSwift
import RxCocoa


private var maxTextFieldLength = [UITextField: Int]()
private var maxTextViewLength = [UITextView: Int]()

extension UITextField {


    @IBInspectable var maxCount: Int {
        get {
            guard let length = maxTextFieldLength[self] else {
                return Int.max
            }
            return length
        }
        set {
            maxTextFieldLength[self] = newValue
            addTarget(
                self,
                action: #selector(limitLength),
                for: UIControlEvents.editingChanged
            )
        }
    }

    @objc
    func limitLength(textField: UITextField) {
        guard let prospectiveText = textField.text,
            prospectiveText.count > maxCount
            else {
                return
        }

        let selection = selectedTextRange
        text = prospectiveText[safe: 0 ..< maxCount]
        selectedTextRange = selection
    }

}

extension UITextView:UITextViewDelegate {

    public func shouldChangeText(in range: UITextRange, replacementText text: String) -> Bool {
        KPLog(text)
        return true
    }

    @IBInspectable var maxCount: Int {
        get {
            guard let length = maxTextViewLength[self] else {
                return Int.max
            }
            return length
        }
        set {

//            if maxTextViewLength[self] == nil {
//                rx.text.skip(1).asObservable()
//                    .subscribe(onNext: { (text) in
//                        guard let text = text else {
//                            return
//                        }
//                        if
//                    }, onError: <#T##((Error) -> Void)?##((Error) -> Void)?##(Error) -> Void#>, onCompleted: <#T##(() -> Void)?##(() -> Void)?##() -> Void#>, onDisposed: <#T##(() -> Void)?##(() -> Void)?##() -> Void#>)
//            }


            maxTextViewLength[self] = newValue
        }
    }

    @objc
    func limitLength(textView: UITextView) {
        guard let prospectiveText = textView.text,
            prospectiveText.count > maxCount
            else {
                return
        }

        let selection = selectedTextRange
        text = prospectiveText[safe: 0 ..< maxCount]
        selectedTextRange = selection
    }

}
